<?php

namespace front\modules\app\controllers;

use front\controllers\WebBaseController;
use goods\services\ShopCategoryProductService;
use common\helpers\ReturnHelper;
use EasyWeChat\Foundation\Application;
use goods\models\ShopCategory;
use goods\services\PanelService;
use wechat\services\AccountService;
use Yii;
use front\models\ProductModel;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\helpers\GoodsHelper;
use yii\helpers\ArrayHelper;
use goods\services\ProductService;
use goods\services\CollectionService;
use backfeed\services\CommentService;
use coupons\services\CouponsGroupService;
use goods\services\CartService;
use goods\services\HistoryService;
use users\services\UserService;
/**
 * ProductController implements the CRUD actions for ProductModel model.
 */
class ProductController extends WebBaseController
{
    private $pid;
    public $enableCsrfValidation = false;
    private $getUserId;
    public $layout=false;
    function init(){
        parent::init();
        $this->pid = isset($_GET['pid']) ? Yii::$app->request->get('pid'):'';
        $this->getUserId = isset($_GET['uid'])&&$_GET['uid'] ? Yii::$app->request->get('uid'):0;
    }

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 刷新页面
     */
    function actionHerfpage(){

        $num = yii::$app->request->get('num') ? yii::$app->request->get('num'):'' ; //商品数量
        $attr = yii::$app->request->get('attr') ? yii::$app->request->get('attr'):'';  //商品属性
        $poid = yii::$app->request->get('poid') ? yii::$app->request->get('poid'):'';  //商品属性

        if($attr){
            $detailInfo = ProductService::ProductInfo($poid);

            if($detailInfo['code']==1){
                WebBaseController::getAjaxDataInfo(3,'商品不存在');
            }
            $rest=$res=$poid=[];
            if(isset($detailInfo['result']['productInfo'])){
                $arr= ArrayHelper::toArray($detailInfo['result']['productInfo']);
                foreach($arr['sku_propValue'] as $k=>$v){
                    $rest[] = array_values($v);
                }
                //判断属性的长度
                if($rest){
                    foreach($rest as $val){
                        if(count($attr)>1){
                            if($val[0]==$attr[0]&&$val[1]==$attr[1]){
                                $poid = $val[2];
                            }
                        }else{
                            if($val[0]==$attr[0]){
                                $poid = $val[1];
                            }
                        }
                    }
                }
            }
            if($poid){
                $sqlNum = $this->vailnum($poid);
                if($num>$sqlNum){
                    WebBaseController::getAjaxDataInfo(2,'商品库存不足');
                }
            }
            $data['pid'] = $poid;
            $detailist = ProductService::ProductInfo($data['pid']);

            if($detailist['code']==1){
                WebBaseController::getAjaxDataInfo(3,'商品不存在',$data);
            }
            $data['num'] = $num;
            WebBaseController::getAjaxDataInfo(0,'success',$data);
        }

    }
    /**
     * Lists all ProductModel models.
     * @return mixed
     */
    public function actionDetail()
    {
        //获取商品详细信息
        $goodsDetail = ProductService::ProductInfo($this->pid);
        if($goodsDetail['code']==1){
            WebBaseController::getAjaxDataInfo(2,'商品不存在');
        }
        $arr['code'] = $goodsDetail['code'];
        $arr['message'] = $goodsDetail['message'];
        $arr=[];
        if(isset($goodsDetail['result']['productInfo'])){
            $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);
            $arr['productInfo'] = isset($arr['pid'])?CommentService::search(['product_id'=>$this->pid,'per-page'=>3,'getByWeb'=>1]):'';  //商品评论数
            $arr['productInfo']['result'] = ArrayHelper::toArray($arr['productInfo']['result']);
            if(isset($arr['productInfo']['result'])){
                foreach($arr['productInfo']['result'] as $k=>$v){
                    $arr['productInfo']['result'][$k]['created_at'] = date('Y-m-d',$v['created_at']);
                    $arr['productInfo']['result'][$k]['attr'] =
                        isset($arr['productInfo']['result'][$k]['product_id']) ? $this->getProductStr($arr['productInfo']['result'][$k]['product_id'],1) :'';
                }
            }

            $arr['newattr'] =$this->getProductStr($this->pid,'','',1); //属性
            $arr['productInfo']['count'] =isset($this->pid)?CommentService::getCount(['product_id'=>$this->pid]):"";  //评论数量
            $arr['productInfo']['collect'] = isset($this->pid)?CollectionService::getCollectionCount($this->pid):'0';   //收藏
            $arr['productInfo']['usr_collect'] = isset($this->pid)&&$this->getUserId ? CollectionService::getUserCollectionCount($this->pid,$this->getUserId):'0';   //收藏
            $arr['productDetail'] = ArrayHelper::toArray($goodsDetail['result']['productDetail']);
            $arr['promotion'] = isset($arr['promotion']) ? $this->getPromotr($arr['promotion']) : '';  //卡券
            $arr['cartCount'] = isset($this->getUserId)&&$this->getUserId ? CartService::cartCount($this->shop_id,$this->getUserId) : 0 ;   //购物车数量
            if(isset($arr['productInfo']['result'])){
                foreach($arr['productInfo']['result'] as $comkey=>$comval){
                    $arr['productInfo']['result'][$comkey]['username'] =UserService::getUserInfo($comval['user_id']);
                    $arr['productInfo']['result'][$comkey]['username'] =ArrayHelper::toArray($arr['productInfo']['result'][$comkey]['username']['result']);
                }
            }
                //商品浏览记录
            if($this->getUserId == 0) {
                $res['user_id'] = $this->getUserId;
                $res['product_id'] = $this->pid;
                $res['title'] = isset($arr['name']) ? $arr['name'] : '';
                $res['pic_url'] = isset($arr['thumb'][0]) ? $arr['thumb'][0] : '';
                $res['price'] = isset($arr['price']) ? $arr['price'] : 0;
                $res['data'] = isset($this->pid) ? $this->getProductStr($this->pid, '') : '';
                HistoryService::add($res);
            }
            //判断商品是否有属性，服务于前端js
            $isAttr = 0;
            $lenAttr = count($arr['saleProp_list']);
            if($lenAttr > 0){
                $isAttr = 1;
            }

            $prodata['data'] = $arr;
            $prodata['pid'] = $this->pid;
            $prodata['isAttr'] = $isAttr;
            $prodata['lenAttr'] = $lenAttr;
            $prodata['qrcode'] = $this->qrcode($this->pid);

            WebBaseController::getAjaxDataInfo(0,'success',$prodata);


        }

    }

    /**
     * 商品的属性信息
     */
    function getProductStr($pid,$type='',$num='',$provalue=''){
        $res=$rest=$rr=[];
        $goodsDetail = ProductService::ProductInfo($pid);
        if(!$goodsDetail){
            WebBaseController::getAjaxDataInfo(5,'商品不存在');
        }
        $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);
        if(isset($arr['item_url_map'])){
            foreach($arr['item_url_map'] as $k=>$v){
                if($pid){
                    if($pid==$v['product_id']){
                        $res = isset($arr['item_url_map'][$k])?$arr['item_url_map'][$k]:array();
                        unset($res['product_id']);
                    }
                }
            }
            //默认显示的
            if($type==1){
                $arr='';
                unset($res['product_id']);
                foreach($res as $key=>$val){
                    $arr.="<em> ".$key."：</em><i>".$val."</i>";
                }
                return $arr;
            }
            //把数量加进去，选择属性的时候用到
            if($type==2){
                $arr='';
                if(isset($res['product_id']))unset($res['product_id']);
                if(isset($res)){
                    foreach($res as $key=>$val){
                        $arr.="<em> ".$key."：</em><i>".$val."</i>";
                    }
                    if($num){
                        $arr.="<em> 数量：</em><i>".$num."</i>";
                    }
                    return $arr;
                }

            }

            //选择属性的时候用到是否选中
            if($provalue){
                $arr=[];
                $rest=[];
                if(isset($arr['sku_propValue'])){
                    foreach($arr['sku_propValue'] as $k=>$v){
                        if($pid){
                            if($pid==$v['product_id']){
                                $rest = $arr['sku_propValue'][$k];
                                if(isset($res['product_id']))unset($res['product_id']);
                            }
                        }
                    }
                }
                if(isset($res)){
                    $rest =  array_flip($rest);
                    foreach($rest as $key=>$val){
                        $rr[$key] =$key;
                    }
                    return $rr;
                }

            }
            return $res;
        }

    }



    /**
     * 检测商品数量
     */
    function vailnum($pid){
        $sql = ProductService::getStock($pid); //库存
        $sqlnum = ArrayHelper::toArray($sql);
        $sqlnum = $sqlnum['stock'];
        return $sqlnum;
    }
    /**
     * 获取对应的卡券信息
     */

    function getPromotr($data){
        $res =$list =  [];
        foreach($data as $k=>$v){
            $res[] =CouponsGroupService::getGroupInfo($v);
        }
        foreach($res as $key=>$val){
            $res[$key]['result'] = ArrayHelper::toArray($val['result']);
            $list[$key] =  $res[$key]['result'];
            $list[$key]['discount'] =isset($res[$key]['discount']) ? $this->setCouponsInfo($res[$key]['discount']):'';
            $list[$key]['product_id'] = isset($res[$key]['product_id']) ? unserialize($res[$key]['product_id']):'';
        }
        return $list;
    }

    /**
     * 将卡券组合
     */
    function setCouponsInfo($data){
        if($data){
            $res='';
            $data = unserialize($data);
            foreach($data as $k=>$v){
                $res.=$k.$v.'<br/>';
            }
            return $res;
        }
    }

    /**
     * 用户领取卡券
     */
    function actionReceive(){
        $data = yii::$app->request->get();
        if($this->getUserId() == 0){
            WebBaseController::getAjaxData(4,'需登录','',$data['callback']);
        }
        if(!$data['group_id']){
            WebBaseController::getAjaxData(2,'卡券不存在');
        }
        $data['user_id'] = $this->getUserId();
        $info = CouponsGroupService::receive($data['group_id'],$data['user_id']);
        if($info['code']==1){
            WebBaseController::getAjaxData(3,$info['message'],'',$data['callback']);
        }
        WebBaseController::getAjaxData(1,'领取成功','',$data['callback']);

    }

    /**
     * 添加收藏
     */
    function actionAddcollect(){

        if($this->getUserId == 0){
            WebBaseController::getAjaxDataInfo(4,'需登录');
        }
        if(!$this->pid){
            WebBaseController::getAjaxDataInfo(3,'商品不存在');
        }
        $res['C_Id'] = $this->getUserId;
        $res['S_Id'] = $this->shop_id;
        $res['P_Id'] =  $this->pid;
        $res['getByWeb'] =  1;
        //判断该用户有没有收藏该商品
        $collect = CollectionService::getCollection($res);
        $list=[];
        if(isset($collect['result'][0])&&$collect['result'][0]){
            $collect=ArrayHelper::toArray($collect['result'][0]);
            CollectionService::remove($collect['ID']);
            $collectCount =CollectionService::getCollectionCount($this->pid);
            $list['count'] = $collectCount;
            $list['type']=2;
            WebBaseController::getAjaxDataInfo(0,'success',$list);
        }else{
            $goods = ProductService::ProductInfo($this->pid);
            $arr=ArrayHelper::toArray($goods['result']);
            $res['p_name'] = isset($arr['productInfo']['name']) ? $arr['productInfo']['name']:'';
            $res['pic'] = isset($arr['productInfo']['thumb'][0]) ? $arr['productInfo']['thumb'][0] : '';
            $res['price'] = isset($arr['productInfo']['price']) ? $arr['productInfo']['price'] : '';
            $res['attributes'] = isset($arr['productInfo']['item_attrText_map']) ?$arr['productInfo']['item_attrText_map'] : '';
            $info = CollectionService::addCollection($res);
            $collectCount = CollectionService::getCollectionCount($this->pid);
            if($info['code']==1){
                WebBaseController::getAjaxDataInfo(2,'收藏失败','',$_GET['callback']);
            }
            $list['count'] = $collectCount;
            $list['type']=1;
            WebBaseController::getAjaxDataInfo(0,'success',$list);
        }
    }

    /**
     * 修改商品，上架，下架的
     */
    function actionChangestatus(){
        $pid = Yii::$app->request->post('pid');
        $status = Yii::$app->request->post('status');
        if(!$pid){
            WebBaseController::getAjaxData(2,'商品不存在');
        }
        if(empty($status)){
            WebBaseController::getAjaxData(3,'请选择修改状态');
        }
        if(ProductService::changeStatus($pid,$status)){
            WebBaseController::getAjaxData(4,'修改成功');
        }
    }

    /**
     * 更新商品信息
     */
    function actionUpdateinfo(){
        $updateInfo = Yii::$app->request->post();
        if(!$updateInfo['pid']){
            WebBaseController::getAjaxData(2,'商品不存在');
        }
        if(ProductService::updateProductInfo($updateInfo)){
            WebBaseController::getAjaxData(3,'修改成功');
        }
    }

    /**
     * 获取热销类目
     */
    function actionHotCategory()
    {
        $shop_id = Yii::$app->request->get();
        if (empty($shop_id)) {
            WebBaseController::getAjaxData(3,'未传递shop_id参数');
        }
        $category = ProductService::hotCategory($shop_id);
        if (empty($category)) {
            WebBaseController::getAjaxData(2,'未查询到店铺对应的类目');
        }
        WebBaseController::getAjaxData(1,$category);
    }

    /**
     * 获取指定类目下商品列表
     * @return array
     */
    public function actionList()
    {
        $category_id = Yii::$app->request->get('category_id');
        $shop_id = Yii::$app->request->get('shop_id');
        if (empty($category_id)) {
            WebBaseController::getAjaxData(3,'未传递category_id参数');
        }
        if (empty($shop_id)) {
            WebBaseController::getAjaxData(4,'未传递shop_id参数');
        }
        $list = ShopCategoryProductService::hotProductList($shop_id,$category_id);
        if ($list['code'] == 1) {
            WebBaseController::getAjaxData(2,'未查询到类目对应的商品信息');
        }
        WebBaseController::getAjaxData(1,$list['result']);
    }

    /**
     * 获取各种类型促销商品列表
     * @return array
     */
    public function actionPromotion()
    {
        $shop_id = Yii::$app->request->post('shop_id');
        $type = Yii::$app->request->post('type');
        if (empty($shop_id)) {
            WebBaseController::getAjaxData(3,'未传递shop_id参数');
        }
        if (($type != 0) && (empty($type))) {
            WebBaseController::getAjaxData(4,'未传递type参数');
        }
        return ProductService::promotionList($shop_id,$type);
    }


    /**
     * Displays a single ProductModel model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProductModel model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ProductModel();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->pid]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProductModel model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->pid]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ProductModel model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProductModel model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ProductModel the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProductModel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionInfo()
    {
        if(!$this->pid){
            WebBaseController::getAjaxData(2,'商品不存在');
        }
        //获取商品详细信息
        $goodsDetail = ProductService::ProductInfo($this->pid);
        $arr['code'] = $goodsDetail['code'];
        $arr['message'] = $goodsDetail['message'];
        $arr['product'] = ArrayHelper::toArray($goodsDetail['result']['productInfo']);

        $collection = CollectionService::getCollectionCount($this->pid);  //商品收藏数
        $arr['productInfo']['collectCount'] = $collection['result']['count'];
//        $arr['productInfo']['collect']['result']['count'] =count(ArrayHelper::toArray($arr['productInfo']['collect']['result']));
        $arr['productInfo']['comment'] = CommentService::search(['product_id'=>$arr['product']['pid'],'per-page'=>3,'getByWeb'=>1]);  //商品评论数
        $arr['productInfo']['comment']['result'] = ArrayHelper::toArray($arr['productInfo']['comment']['result']);
        $arr['productInfo']['comment']['result']['count'] =count(ArrayHelper::toArray($arr['productInfo']['comment']['result']));
        $arr['productDetail'] = ArrayHelper::toArray($goodsDetail['result']['productDetail']);
        $arr['product']['promotion'] = $this->getPromotr($arr['product']['promotion']);
        $arr['product']['promotion'] = ArrayHelper::toArray($arr['product']['promotion']);
        return $this->render('info',['data'=>$arr]);
    }

    /**
     *  生成微信临时二维码
     * @param $pid
     * @return string
     */
    public function qrcode($pid){
        $cache = \yii::$app->cache;
        $pqrcode = $cache->get(self::ORIGINAL_ID . 'qrcode_' . $pid);
        if(time() - intval($pqrcode['create_time']) >= 30 * 24 * 3600){
            $config = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($config);
            $qrcode = $app->qrcode;
            $result = $qrcode->temporary($pid % 1000000, 30 * 24 * 3600);
            $ticket = $result->ticket;// 或者 $result['ticket']
            $url = $qrcode->url($ticket);
            $qqrcodeInfo = [
                'create_time' => time(),
                'qrcode' => $url
            ];
            $cache->set(self::ORIGINAL_ID . 'qrcode_' . $pid, $qqrcodeInfo);
            //$url : 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQHR8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL1JVVGQzUkRtclVqVVpLY0UxV3JjAAIEE5YHVwMEAOkHAA=='
            return $url;
        }
        return $pqrcode['qrcode'];

    }

    /**
     * 根据店铺id获取所有的类目id(大屏类目)
     * @return string
     */
    public function actionCategory()
    {
        //shop_id默认shopbox为1001
        $shop_id = 1001;
        return json_encode(\backend\modules\v1\models\ShopCategory::getCategoryInfo($shop_id,2));
    }

    /**
     * 根据店铺id获取所有的类目id(中屏类目)
     * @return string
     */
    public function actionSmallCategory()
    {
        //shop_id默认shopbox为1001
        $shop_id = 1001;
        return json_encode(\backend\modules\v1\models\ShopCategory::getCategoryInfo($shop_id,3));
    }

    /**
     * 根据商品店铺ID和类目ID获取对应的商品列表
     * @return string
     */
    public function actionCategoryProduct()
    {
        $shop_id = 1001;
        $shop_cid = Yii::$app->request->get('shop_cid');
        if (!isset($shop_cid)) {
            return json_encode(ReturnHelper::error('未传递shop_cid'));
        }
        $data = ShopCategoryProductService::panelSearchList(['shop_id'=>$shop_id,'shop_cid' => $shop_cid,'type'=>2]);
        foreach ($data as $k => $v) {
            $data[$k] = ArrayHelper::toArray($v);
        }
        foreach ($data as $k=>$v) {
            $pic = PanelService::getInfo($v['pid']);
            if (empty($pic['pic'])) {
                continue;
            } else {
                $data[$k]['pic'] = $pic['pic'];
            }
        }
        return json_encode($data);
    }

    /**
     * 小屏类目商品列表
     * @return string
     */
    public function actionSmallProduct()
    {
        $shop_id = 1001;
        $shop_cid = Yii::$app->request->get('shop_cid');
        $data = Yii::$app->request->get();
        if (!isset($shop_cid)) {
            return json_encode(ReturnHelper::error('未传递shop_cid'));
        }
        if (!isset($data['page'])) {
            return json_encode(ReturnHelper::error('未传递page参数'));
        }
        if (!isset($data['pre-page'])) {
            return json_encode(ReturnHelper::error('未传递pre-page参数'));
        }
        $data = ShopCategoryProductService::smallSearchList(['shop_id'=>$shop_id,'shop_cid' => $shop_cid,'type'=>3]);
        foreach ($data as $k => $v) {
            $data[$k] = ArrayHelper::toArray($v);
        }

        $info = [];
        foreach ($data as $k=>$v) {

            $product = ArrayHelper::toArray(ProductService::ProductInfo($v['pid']));
            if ($product['code'] == 1){
                continue;
            }
            $product = $product['result']['productInfo'];
            $info[$k]['pid'] = $product['pid'];
            $info[$k]['name'] = $product['name'];
            $img = \goods\models\Product::getThumbList($v['pid']);
            $info[$k]['thumb'] = $img.'@1e_1c_0o_0l_750h_750w_100q.jpg';
            $info[$k]['price'] = $product['price'];
        }
        return json_encode($info);
    }

    /**
     * 根据商品ID获取对应的上传商品图片和商品信息
     * @return string
     */
    public function actionProductDetail()
    {
        $pid = Yii::$app->request->get('pid');
        if (!isset($pid)) {
            return json_encode(ReturnHelper::error('未传递pid'));
        }
        $productInfo = ProductService::ProductInfo($pid);
        $productInfo = $productInfo['result']['productInfo'];
        $panelInfo = PanelService::getInfo($pid);
        $panelInfo['price'] = $productInfo['price'];
        $panelInfo['title'] = $productInfo['name'];
        $panelInfo['video'] = $productInfo['video']?$productInfo['video']:'1';
        $panelInfo['thumb'] = $productInfo['thumb'];
        $panelInfo['qrcode'] = $this->qrcode($pid);
        return json_encode($panelInfo);
    }

}
